package com.sita.redsun.other;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by zhebinwang on 2017/3/29.
 * 这个类是为了发送到远程mq上做准备的
 * 实际无用，是另外一种方式
 */
public class MQSenderTarget {


    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //    连接地址
    private static final String BROKEURL = "tcp://localhost:61616";//此处改为远程地址

    private static Session session = null;
    private static MessageProducer messageProducer;

    public  int init() throws JMSException {
        //连接工厂
        ConnectionFactory connectionFactory;
        //连接
        Connection connection = null;
        //会话 接受或者发送消息的线程

        //消息的目的地
        Destination destination;
        //消息生产者

        //实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://localhost:61616");
        try {
            //    获取连接
            connection = connectionFactory.createConnection();
            //    启动连接
            connection.start();
            //    创建session
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);

            //    创建一个名称为fire.queue的消息队列
            destination = session.createQueue("fire.queue");
            //    创建消息生产者
            messageProducer = session.createProducer(destination);
            //    发送消息
            //sendMessage(session, messageProducer);
            // 提交会话


        } catch (Exception e) {
            e.printStackTrace();
        }finally{
          /*  if (null != session) {
                session.close();
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }*/
        }

        return 0;
    }


    public static void sendMessage(String msg) throws Exception{
        //未初始化不进行操作
        if (session==null || messageProducer==null){
            return;
        }

        TextMessage textMessage  = session.createTextMessage();
        textMessage.setText(msg);

        messageProducer.send(textMessage);
        session.commit();
    }

}
